package com.tanhua.dubbo.api.impl;

import com.tanhua.domain.mongo.Voice;
import com.tanhua.domain.mongo.VoiceUser;
import com.tanhua.dubbo.api.SoundApi;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import java.util.List;
import java.util.Random;

@Service(timeout = 1000000)
public class SoundApiImpl implements SoundApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public void save(Voice voice) {
        mongoTemplate.save(voice);
    }

    @Override
    public Voice randomFind(Long userId) {

        // 创建查询对象，排除用户本身的传音
        Query query = new Query(Criteria.where("userId").ne(userId));
        List<Voice> voiceList = mongoTemplate.find(query, Voice.class);

                // 如果集合中有2条及以上数据
                if (voiceList != null && voiceList.size() > 1) {
                    // 取集合的长度，设置随机值
                    int size = voiceList.size();
                    Random rand = new Random();
                    // 创建查询对象,随机查询一条传音
                    Voice voiceId = voiceList.get(rand.nextInt(size));
                    Query queryList = new Query(Criteria.where("userId").is(voiceId.getUserId()));
                    Voice voice = mongoTemplate.findOne(queryList, Voice.class);

                    return voice;
                }

                if (voiceList.size() == 1) {
                    // 如果集合中只有1条数据
                    for (Voice voice : voiceList) {
                        return voice;
                    }
                }
        return null;
    }

    @Override
    public VoiceUser findById(Long userId) {

        // 创建查询对象
        Query query = new Query(Criteria.where("userId").is(userId));
        VoiceUser voiceUser = mongoTemplate.findOne(query, VoiceUser.class);
        // 判断是否存在
        if (voiceUser != null) {
            return voiceUser;
        }
        voiceUser = new VoiceUser(userId, 10L);
        mongoTemplate.save(voiceUser);
        return voiceUser;
    }

    @Override
    public void updateVoiceUser(VoiceUser voiceUser) {

        Query query = new Query(Criteria.where("userId").is(voiceUser.getUserId()));
        Update update = new Update();
        update.set("remainingTimes", voiceUser.getRemainingTimes());
        mongoTemplate.updateMulti(query, update, VoiceUser.class);
    }

    @Override
    public void update(Voice voice, Integer reception) {
        Query query = new Query(Criteria.where("_id").is(voice.getId()));
        Update update = new Update();
        update.set("reception", reception);
        mongoTemplate.updateMulti(query, update, Voice.class);
    }
}
